<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="/WEB-INF/tld/c.tld" prefix="c" %>
<%@ taglib uri="/WEB-INF/tld/ui.tld" prefix="ui" %>
<%
	String path = request.getContextPath();
%>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>纸质票据新增</title>
<jsp:include page="../../import.jsp" flush="true" />
</head>
<body class="iframeBody">

<div class="Wrapper">
	<div>
            <div id="pageInTab" class="pageInTab">
                    <form id="cust_invoice_add_form">
                        <div class="fieldset1 tabel_col clearFix">
                            <div class="fieldBox col_33">
			                    <div class="label">客户名称</div>
			                    <div class="field">
			                        <input name="cstNm" id="cstNm" disabled="disabled" type="text" class="ui-textbox" value="${cstNm }" validate="{required:true, maxlength:20}">
			                    </div>
			                </div>

			                <div class="fieldBox col_33">
			                    <div class="label">项目所属机构</div>
			                    <div class="field">
			                        <input name="orgNm" id="orgNm" disabled="disabled" type="text" class="ui-textbox" value="${orgCdNm }" validate="{required:true, maxlength:60}">
			                    </div>
			                </div>

                            <div class="fieldBox col_33">
                                <div class="label">收件人</div>
			                    <div class="field">
			                        <input name="rcverNm" id="rcverNm" type="text" class="ui-textbox" value="" placeholder="无特殊情况,请填写商助姓名." validate="{required:true, maxlength:10}">
			                        <span class="requiredSymbol">*</span>
			                    </div>
                            </div>
                            <div class="fieldBox col_33">
			                     <div class="label">收件人联系电话</div>
						        <div class="field">
						           <input name="rcverTel" id="rcverTel" type="text" class="ui-textbox" value="" placeholder="无特殊情况,请填写商助电话." validate="{required:true, maxlength:15}">
						           <span class="requiredSymbol">*</span>
						        </div>
			                </div>
                            <div class="fieldBox col_33">
                                <div class="label">开具方式</div>
                                <div class="field">
                                    <input name="applyCd" id="applyCd" type="text" class="ui-textbox" value="纸质发票" disabled>
                                </div>
                            </div>
                            <div class="fieldBox col_33">
                                <div class="label">客户类型</div>
                                <div class="field">
                                    <input name="cstTypNm" id="cstTypNm" type="text" class="ui-textbox" value="${cstTypNm}" disabled>
                                </div>
                            </div>
			                <div class="fieldBox col_50">
			                    <div class="label">收件地址</div>
			                    <div class="field">
			                        <input name="rcvAddr" id="rcvAddr" type="text" class="ui-textbox" value="" placeholder="无特殊情况,请填写商助地址." validate="{required:true, maxlength:60}">
			                        <span class="requiredSymbol">*</span>
			                    </div>
			                </div>
                            <div class="fieldBox col_50">
                                <div class="label">发票流水号</div>
                                <div class="field">
                                    <input name="invoiceCode" id="invoiceCode" type="text" class="ui-textbox" value="" disabled>
                                </div>
                            </div>
			                <div class="fieldBox col_33">
			                    <div class="label">是否提前开票</div>
			                    <div class="field">
			                        <c:forEach items="${ynList }" var="kv" begin="0" step="1" varStatus="status">
			                            <c:if test="${kv.key == 0}">
			                                <input type="radio" value="${kv.key }" name="isPreInv" checked />${kv.value }
			                            </c:if>
										<c:if test="${kv.key != 0}">
			                                <input type="radio" value="${kv.key }" name="isPreInv" />${kv.value }
			                            </c:if>
									</c:forEach>
			                    </div>
			                </div>

			                <div class="fieldBox col_33">
			                     <div class="label">开票人电话</div>
						        <div class="field">
						           <input name="invTel" id="invTel" type="text" class="ui-textbox" value="" validate="{required:true, maxlength:15}">
						           <span class="requiredSymbol">*</span>
						        </div>
			                </div>

			                <div class="fieldBox col_33">
			                    <div class="label">开票人开户行</div>
			                    <div class="field">
			                         <select name="invBkCd" id="invBkCd" data-value="" >
			                            <option value="">请选择</option>
			                            <c:forEach items="${selectBkCdList }" var="kv">
											<option value="${kv.key }">${kv.value }</option>
										</c:forEach>
			                		 </select>
			                    </div>
			                </div>

				            <div class="fieldBox col_33">
			                     <div class="label">开票人帐号</div>
						        <div class="field">
						           <input name="invAccNo" id="invAccNo" type="text" class="ui-textbox" value="" >
						        </div>
			                </div>

			                <div class="fieldBox col_33">
			                     <div class="label">纳税人识别号</div>
						        <div class="field">
						           <input name="invTaxId" id="invTaxId" type="text" class="ui-textbox" value="" validate="{required:false, maxlength:30}">
						           <span class="requiredSymbol">*</span>
						        </div>
			                </div>

			                <div class="fieldBox col_100">
			                    <div class="label">发票抬头</div>
			                    <div class="field">
			                        <input name="invTitle" id="invTitle" type="text" class="ui-textbox" value="${cstNm }" validate="{required:false, maxlength:20}" readonly>
                                    <span style="color: red;">直租/经营租赁法人客户申请专票需填写开票人开户行、开票人账号、开票地址。</span>
			                    </div>
			                </div>

			                <div class="fieldBox col_100">
			                    <div class="label">开票地址</div>
			                    <div class="field">
			                        <input name="invAddr" id="invAddr" type="text" class="ui-textbox" value="" >
			                    </div>
			                </div>

			                <div class="fieldBox col_100">
								<div class="label">资料上传</div>
								<div class="field">
				                   	<jsp:include page="../../system/sysUlFilesRec/sysSysUlFilesRecUpload2.jsp" flush="true" >
				                   		<jsp:param name="filePath" value="invoice"/>
				                   	</jsp:include>

								</div>
							</div>
			                 <!-- hide data -->
					        <div class="fieldBox col_100" style="display:none;">
					          <div class="field">
					              <input name="orgCd" id="orgCd" type="text" class="ui-textbox" value="${orgCd}">
					              <input name="extPaySchMId" id="extPaySchMId" type="text" class="ui-textbox" value="${extPaySchMId}">
					              <input name="extPrjId" id="extPrjId" type="text" class="ui-textbox" value="${extPrjId}">
					          </div>
					        </div>
                        </div>
                    </form>
                        <!-- 支付表列表 -->
						<jsp:include page="invoiceApplyGrid.jsp" flush="true"></jsp:include>
                    </div>
        </div>
</div>

	<script>
        var flag = '${flag}';
        var cstId = '${cstId}';
        var grid;
		$(function() {
		   $("#cust_invoice_add_form").ligerForm({
                validate: true
           });
		   $("#cst_invoice_start_flow_btn").click(function (event) {
			    //保存开票信息:返回开票ID
				var _id;
	            var modelTyp = FlowConstant.FLOW_MODEL_TYP_INVOICE;  //流程业务类型:开票
	            if(StringUtils.isEmpty(modelTyp)){
	            	console.log("modelTyp is null");
	            	return;
	            }
	            //验证数据状态
	            var pass = validData();
				if(!pass){
					return;
				}
	    		var formData = getPassValidData();

	            var flowDialog = $.ligerDialog.SQopen({
	                url: '<%=path%>/flow/flow/toForStartListPage.do',
	                urlParms:{modelTyp:modelTyp},
	                width: 700,
	                height:400,
	                title : '请选择要发起的流程',
	                buttons: [{
			                text: "确定", type: 'ok', cls: 'sq-button sq-button-round',
			                onclick: function (item, Dialog) {
			                    if (Dialog.onOk) Dialog.onOk();
			                }
			            }, {
			                text: "取消", type: 'cancel', cls: 'sq-button sq-button-round',
			                onclick: function (item, Dialog) {
			                    if (Dialog.onCancel) Dialog.onCancel();
			                }
			            }
			        ],
	                onClose: function () {
	                	var json = flowDialog._DATA;
	                	if(!json){
		                	return;
	                	}

	                	formData["procDefKey"] = json.procDefKey;
	    	    		formData["procDefId"] = json.procDefId;
	    	    		formData["procNo"] = json.procNo;
	    	    		//alert(JSON.stringify(formData));
	    	    		//return;
	                	var wait_dialog=$.ligerDialog.SQalert({content: LogUtils.LOG_CMM_DATA_LOADING, SQ_type: "waitting",onClose: function () {}});
	            		$.ajax({
	                		type: 'post',
	                		dataType:'json',
	                		data:formData,
	                		url: '<%=path%>/invoice/prjbillapply/addFlowStart.do',
	                		success:function(msg){
	                			wait_dialog.close();
	                			 if(msg.success == 1){
	                				 if(msg.data){
										 alertNextFlowAssign(msg.data);
	                				 }else{
	                					 UIUtils.alertSuccess(msg.info);
	                				 }
	                				 grid.reload();
	                			 }else{
	                				 UIUtils.alertError(msg.info);
	                			 }
	                		}
	                	});
	                }
	            });
	        });
	       //是否提前结清按钮事件
		   $("[name=isPreInv]").click(function(event) {
		       var isPreInvVal =$(this).ligerGetRadioManager().input.val();
		       //alert(isPreInvVal);
		       var _cstId = $("#cstId").val();
			   //支付表ID和项目ID是非正常开票流程使用的
			   var extPaySchMId = $("#extPaySchMId").val();
			   var extPrjId = $("#extPrjId").val();
			   if(StringUtils.isEmpty(extPaySchMId)){
				   extPaySchMId = "";
			   }

			   if(StringUtils.isEmpty(extPrjId)){
				   extPrjId = "";
			   }

			   grid.setParm("extPaySchMId",extPaySchMId);
			   grid.setParm("extPrjId",extPrjId);
			   grid.setParm("cstId",_cstId);
		       if(isPreInvVal == 0){
				   grid.setParm("isPreInv","0");
		       }else{
		    	   grid.setParm("isPreInv","1");
		       }
		       grid.reload();
		   });

		});

	    //提交验证数据是否添加正确以及是否选择了数据
		function validData(){
	        var cstTypCd = '${cstTypCd}';
	        var invTaxId = $("#invTaxId").val();
	        if ("2" == cstTypCd && (null == invTaxId || "" == invTaxId)) {
                $.ligerDialog.SQalert({content: "请填写纳税人识别号", SQ_type: "warning"});
                return false;
            }
			var ligerForm = liger.get("cust_invoice_add_form");
            if (!ligerForm.valid()) {
                UIUtils.alertWarning(LogUtils.LOG_CMM_MUST_FIX_ITEM_INFO);
                return false; //验证不通过，不执行以下代码
            }
            var formData = ligerForm.getData();

            //获取Grid数据
            var _grid = grid.getSelectedRows();
            if(_grid.length == 0){
    			$.ligerDialog.SQalert({content: LogUtils.LOG_CMM_SELECT_MORE_ROW, SQ_type: "warning"});
    			return false;
    		}
    		var _data = [];
    		var pass = true;
    		var validNm = "";
    		for ( var index in _grid) {
    			if(!_grid[index].billTypCd){
    				pass = false;
    				validNm = _grid[index].feeTypCdNm;
    				break;
    			}
    		}

    		if(!pass){
    			$.ligerDialog.SQalert({content: "请填写费用项["+validNm+"]开票类型", SQ_type: "warning"});
    			return false;
    		}
    		return pass;
		}

	    //直接获取验证可提交数据
	    function getPassValidData(){
	    	var ligerForm = liger.get("cust_invoice_add_form");
	    	//验证通过后获取数据
            var formData = ligerForm.getData();
            var _isPreInv = $('input[name="isPreInv"]:checked ').val();
            formData["isPreInv"] = _isPreInv;
            //获取Grid数据
            var _grid = grid.getSelectedRows();
    		formData["grid"] = JSON.stringify(_grid);
            formData["cstId"] = cstId;
    		//附件
    		var docArray = JSON.stringify(getUploadResultParams());
            formData["docArray"] = docArray;
    		//alert(JSON.stringify(formData));
    		return formData;
	    }

		//保存
		function save(){
			var pass = validData();
			if(!pass){
				return;
			}
    		var formData = getPassValidData();
    		var url = '<%=path%>/invoice/prjbillapply/add.do';
            $.ligerDialog.confirm("保存后将生成一条申请数据,确认保存吗?", function (flag) {
                if(flag == false)return;
                AjaxUtils.ajaxPost(url, formData, saveCallback, true);
            });

		}

		//新增回调
		function saveCallback(msg){
			if(msg.success == 1){
				 UIUtils.alertSuccess(msg.info);
				 reloadGrid();
				 //alert(msg.data);
			 }else{
				 UIUtils.alertError(msg.info);
			 }
		}

		//重新加载Grid
		function reloadGrid(){
			   var isPreInvVal = $('input[name="isPreInv"]:checked').val();
			   var _cstId = $("#cstId").val();
			   //支付表ID和项目ID是非正常开票流程使用的
			   var extPaySchMId = $("#extPaySchMId").val();
			   var extPrjId = $("#extPrjId").val();
			   if(StringUtils.isEmpty(extPaySchMId)){
				   extPaySchMId = "";
			   }

			   if(StringUtils.isEmpty(extPrjId)){
				   extPrjId = "";
			   }

			   grid.setParm("extPaySchMId",extPaySchMId);
			   grid.setParm("extPrjId",extPrjId);
			   grid.setParm("cstId",_cstId);
			   //如果有变动则要更改列表数据,是为提前结清,需要把所有要开票的数据列出来,如果为正常开票则只显示已经核销完成的数据。(两者都不包含已经开完和正在开票中的数据)
		       if(isPreInvVal == 0){
				   grid.setParm("isPreInv","0");
		       }else{
		    	   grid.setParm("isPreInv","1");
		       }
		       grid.reload();
		}

		function alertNextFlowAssign(key) {
			debugger
			var url = '<%=path%>/flow/flow/getFlowNextAssigne.do?key=' + key;
			var wait_dialog = $.ligerDialog.SQalert({
				content: LogUtils.LOG_CMM_DATA_LOADING,
				SQ_type: "waitting",
				onClose: function () {
				}
			});
			setTimeout(function () {
				$.ajax({
					type: 'post',
					dataType: 'json',
					url: url,
					success: function (msg) {
						wait_dialog.close();
						if (msg.success == 1) {//成功发起流程
							$.ligerDialog.SQalert({
								SQ_showButtons: true,
								SQ_onBtnclick: function (item, Dialog) {
									//关闭当前Tab
									Remove_navTab();
									frameElement.dialog.close();
								},
								content: msg.info
							});
						} else if (msg.success == 0) {//错误
							UIUtils.alertErrorHold1(msg.info);
						}
					}
				});
			}, 8000);
		}
	</script>

</body>
</html>